﻿using AutoMapper;
using Code.Entity;
using Code.Repsitory.Menus;
using Code.Services.Menus.Dto;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Code.Services.Menus
{
    public class MenuService : IMenuService
    {
        private readonly IMenuRepository repository;
        private readonly IHttpContextAccessor httpContext;
        private readonly IMapper mapper;

        public MenuService(IMenuRepository repository, 
            IHttpContextAccessor httpContext,
            IMapper mapper
            )
        {
            this.repository = repository;
            this.httpContext = httpContext;
            this.mapper = mapper;
        }

        public List<TreeDto> GetTreeData()
        {
            var list = repository.Queryable().Where(m => m.ParentId == 0).ToList();

            List<TreeDto> treeDtos = new List<TreeDto>();

            foreach (var item in list)
            {
                TreeDto dto = new TreeDto {
                    ComponentPath = item.ComponentPath,
                    CreateByName = item.CreateByName,
                    CreateTime = item.CreateTime,
                    Icon = item.Icon,
                    IsShow = item.IsShow,
                    MenuId = item.MenuId,
                    MenuName = item.MenuName,
                    Route = item.Route
                };
                RecursionNodes(dto);

                treeDtos.Add(dto);
            }

            return treeDtos;
        }


        public void RecursionNodes(TreeDto dto)
        {
            var list = repository.Queryable().Where(m => m.ParentId == dto.MenuId).ToList();
            foreach (var item in list)
            {
                TreeDto subdto = new TreeDto
                {
                    ComponentPath = item.ComponentPath,
                    CreateByName = item.CreateByName,
                    CreateTime = item.CreateTime,
                    Icon = item.Icon,
                    IsShow = item.IsShow,
                    MenuId = item.MenuId,
                    MenuName = item.MenuName,
                    Route = item.Route
                };
                dto.children.Add(subdto);
                RecursionNodes(subdto);
            }
        }

        public bool CreateMenu(MenuDto dto)
        {
            try
            {
                repository.Insert(mapper.Map<Menu>(dto));
                return true;
            }
            catch (Exception e)
            {
                throw;
            }
        }
    }
}
